package com.example.myproject.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;

import java.util.HashSet;
import java.util.Set;
public class AuthRealm extends AuthorizingRealm {
    /*
     * @Autowired UserService userService;
     * 
     * @Autowired RoleService roleService;
     * 
     * @Autowired LoginLogService loginLogService;
     */

    public AuthRealm() {
        super();
    }

    /**
     * 获取用户拥有的角色和对应的权限
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        /* 这里编写授权代码 */
        Set<String> roleNames = new HashSet<String>();
        // roleNames.add("admin");
        SimpleAuthorizationInfo AuthorizationInfo = new SimpleAuthorizationInfo(roleNames);
        // AuthorizationInfo.setObjectPermissions(objectPermissions)
        // AuthorizationInfo.addRole(roleNames);
        return AuthorizationInfo;
    }

    public void addStringPermisions(SimpleAuthorizationInfo t) {
        Set<String> permissions = new HashSet<String>();
        permissions.add("user.do?myjsp");
        permissions.add("login.do?main");
        permissions.add("login.do?logout");
        permissions.add("user.do?notmyjsp");
        t.setStringPermissions(permissions);
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        /* 这里编写认证代码 */
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        // User user = securityApplication.findby(upToken.getUsername());
        ShiroUser user = new ShiroUser();
        user.setUsercode(token.getUsername());
        user.setUserName(token.getUsername());
        //user.setPassword(token.getPassword());
        if(!"admin".equals(token.getUsername())){
            return null;
        }
        System.out.println("getname =====" + getName()+",passwored:"+token.getCredentials().toString());
        return new SimpleAuthenticationInfo(user, token.getPassword(), getName());
        //return null;
    }
    public void clearCachedAuthorizationInfo(String principal) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
        clearCachedAuthorizationInfo(principals);
    }
}
